import type { PagesType } from './types/pages';
import type { QueryType } from './types/index';
import { useUserStoreWithOut } from '@/store/modules/user';
import { navigateTo, switchTab, redirectTo, reLaunch } from '.';
import { TabbarPageEnum } from '@/enums/pageEnum';

const whiteList: PagesType[] = [
  'loginPhone',
  'startPage',
  'resourceNavigation',
  'home',
  'activity',
  'activityDetails',
  'personCard',
  'businessCard',
  'webview',
  'userAgreement',
  'informationType',
  'weChatOfficialAccountLink',
  'richDetails',
  'systemIntroduction',
  'photoAlbumManage',
  'photoAlbumDetails',
  'supplyDemandSquare',
  'supplyDemandDetails',
  'boPromotionalPage'
]

export const adminPermissionRouteList: PagesType[] = [
  'memberManage',
  'memberAudit',
  'paymentManagement',
  'photosManagement',
  'messageManagement',
  'contactReview',
  'cooperationList',
  'applyCooperation',
  'intendedMembers',
  'serviceForm',
  'activityManage'
]

/**
 * 路由守卫(跳转前执行)
 * @param name 路由别名
 * @param options 页面参数
 * @returns Promise<any>
 */
export function beforeEach(to: { name: PagesType, options?: QueryType }, routeType: 'navigateTo' | 'switchTab' | 'redirectTo' | 'reLaunch'): Promise<any> {
  return new Promise(async (resolve, reject) => {
    const { token, userInfo, wxLogin, checkRouterPermission } = useUserStoreWithOut()
    if (whiteList.includes(to.name)) return resolve('success')

    function success() {
      const name = to.name as any
      const options = to.options
      switch (routeType) {
        case 'navigateTo':
          navigateTo({ name, options })
          break;
        case 'switchTab':
          switchTab(name)
          break;
        case 'redirectTo':
          redirectTo({ name, options })
          break;
        case 'reLaunch':
          reLaunch({ name, options })
          break;
      }
    }
    if (!token) await wxLogin()

    if (routeType !== 'switchTab' && !userInfo.phonenumber && !whiteList.includes(to.name)) {
      navigateTo({ name: 'loginPhone', options: { success } })
      reject('未授权手机号')
      return
    }

    if (routeType !== 'switchTab' && adminPermissionRouteList.includes(to.name) && !checkRouterPermission(to.name)) {
      uni.showModal({
        title: '提示',
        content: '您没有权限访问该页面',
        confirmText: '回到首页',
        showCancel: false,
        success: function (res) {
          switchTab(TabbarPageEnum.BASE_HOME)
        }
      })
      reject('未授权路由')
      return
    }

    resolve('success');
  });
}

/**
 * 路由跳转后执行
 * @param name 路由别名
 * @param options 页面参数
 * @returns
 */
export function afterEach(name: PagesType, options?: QueryType): void { }

/**
 * 路由跳转错误信息
 * @param name 路由别名
 * @param options 页面参数
 */
export function Error(error: unknown, name: PagesType, options?: QueryType): void {
  console.error(name + ' => ');
  console.error(error);
}
